const fp = require('lodash/fp')
// const { Maybe, Container } = require('./support')

// 以下是习题答案:
//公共类
class Maybe {
	static of (value) {
		return new Maybe(value)
	}
	constructor(value) {
		this._value = value;
	}
	map(fn) {
		return this.IsNothing() ? Maybe.of(undefined) : Maybe.of(fn(this._value))
	}
	IsNothing() {
		return this._value === null || this._value === undefined
	}
	JudeType() {
		let val = this._value;
		let status = '';
		if (fp.isNull(val)) {
			status = null;
		} else if (fp.isUndefined(val)) {
			status = undefined;
		} else {
			let num = fp.flowRight(fp.toNumber, fp.first, fp.split(""))(val);
			fp.isNaN(num) ? status = NaN : status = num;
		}
		return Maybe.of(status)
	}
}

class Container {
	static of (value) {
		return new Container(value)
	}
	constructor(value) {
		this._value = value;
	}
	map(fn) {
		return Container.of(fn(this._value));
	}
	IsNothing() {
		return this._value === null || this._value === undefined
	}
}


//习题一
function ex1() {
	let fn = fp.add(1);
	var c = fp.map(fn, arguments[0])
	return c;
}

let maybe = Maybe.of([5, 6, 1])
console.log(maybe.map(ex1))

//习题二
function ex2() {
	return fp.first(arguments[0])
}

let xs = Container.of(['do', 'ray', 'me', 'fa', 'so', 'la', 'ti', 'do'])
console.log(xs.map(ex2))

//习题三
function ex3() {
	let user = {
		id: 2,
		name: 'Albert'
	}

	let safeProp = fp.curry(function(x, o) {
		return Maybe.of(o[x])
	})

	let getFirst = function(json, name) {
		let first = {};
		let p = fp.flowRight(fp.first, fp.split(''));
		first.name = p(json['name'])
		return first;
	}
	return safeProp('name', getFirst(user, 'name'))

}
console.log(ex3())

//习题四
function ex4(val) {
	let maybe = Maybe.of(val)
	return maybe.JudeType()
}
console.log(ex4('7R')) // Maybe { _value: 7 }
console.log(ex4('7.6B')) // Maybe { _value: 7 }
console.log(ex4('8.2G')) // Maybe { _value: 8 }

console.log(ex4(null)) // Maybe { _value: null }
console.log(ex4(undefined)) // Maybe { _value: undefined }

console.log(ex4('i7.5')) // Maybe { _value: NaN }
console.log(ex4('abc')) // Maybe { _value: NaN }
